package br.com.adimoveis.util.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

public class TogglePanel extends JPanel{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Map<JToggleButton, JComponent> paginas;
	
	private JComponent currentComponent;
	
	private JPanel buttonPanel;
	
	private JPanel borderPanel;
	
	private ButtonGroup group;
	
	private List<ActionListener> listeners;
	
	
	public TogglePanel(){
		super(new BorderLayout());
		listeners = new ArrayList<ActionListener>();
		
		paginas = new HashMap<JToggleButton, JComponent>();
		FlowLayout layout = new FlowLayout();
//		layout.setVgap(0);
		
		
		buttonPanel = new JPanel(layout);
		group = new ButtonGroup();
		
		borderPanel = new JPanel(new BorderLayout()){

			private static final long serialVersionUID = 1L;
			
			@Override
			public Insets getInsets() {
				return new Insets(0,9,9,9);
			}
			
		};
		borderPanel.add(buttonPanel, BorderLayout.CENTER);
		add(borderPanel, BorderLayout.SOUTH);
		setBackground(Color.WHITE);
		//buttonPanel.setBackground(Color.WHITE);
		borderPanel.setBackground(Color.WHITE);
		buttonPanel.setBorder(BorderFactory.createEtchedBorder());
	}
	
	public void addPage(String title, Icon icon, JComponent component, boolean isSelected){
		JToggleButton toggle = new ToggleButton(title,icon);
		buttonPanel.add(toggle);
		paginas.put(toggle, component);
		group.add(toggle);
		
		toggle.addActionListener(new ToggleListener());
		toggle.setSelected(isSelected);
		
		if(isSelected){
			add(component, BorderLayout.CENTER);
			currentComponent = component;
		}
	}
	
	public void addActionListener(ActionListener listener){
		this.listeners.add(listener);
	}
	
	private class ToggleListener implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			JToggleButton toggle = (JToggleButton) e.getSource();
			
			if(!toggle.isSelected()){
				return;
			}
			
			if(currentComponent != null){
				remove(currentComponent);
			}
			
			currentComponent = paginas.get(toggle);
			add(currentComponent, BorderLayout.CENTER);
			repaint();
			revalidate();
			fireSelectionChanged(currentComponent);
		}
	}
	
	private void fireSelectionChanged(JComponent currentComponent){
		ActionEvent evt = new ActionEvent(currentComponent,0,"");
		
		for(ActionListener listener : listeners){
			listener.actionPerformed(evt);
		}
	}
}
